const wssrouter = require('koa-router')()
const {msg} = require("../models/msg")
const {user} = require("../models/user")
const {verify} = require("../utils/auth")
const response = require("../utils/response")
const {transport} = require("../utils/email")
const {HEARTBEAT_INTERVAL, CLIENT_TIMEOUT} = require("../utils/constData")
var uws = []
const refreshListInfo = async (uws) => {
    let list = await user.find()
    uws.forEach(e => {
        let obj = {
            type: 'list',
            data: list
        }
        e.send(JSON.stringify(obj))
    })

}
const dealLastWord = (id, obj) => {
    return new Promise(async (resolve, reject) => {
        let res = await user.findOne({
            _id: id
        })
        if (res) {
            let index = res.lastMsg.findIndex(e => e.fid === obj.fid && e.tid === obj.tid)
            if (index === -1) {
                res.lastMsg.push(obj)
            } else {
                res.lastMsg[index]=obj
            }
            res.save().then(() => {
                console.log('保存最后一次聊天信息成功')
                resolve(0)
            }).catch((err) => {
                console.log('保存最后一次聊天信息失败', err)
                reject(1)
            })

        } else {
            reject(1)
            console.log('保存最后一次聊天信息错误')
        }
    })


}
const refreshOrCreateUserInfo = async (uws, id) => {
    user.findOne({
        _id: id
    }).then(res => {
        if (res) {
            user.findOneAndUpdate(
                {_id: id}, {
                    $set: {
                        isOnline: true,
                        loginTime: new Date().getTime()
                    }
                }, {returnDocument: "after"}).then(res => {
                refreshListInfo(uws, id)
            })
        } else {
            console.log('数据库中无此用户，非法用户')

        }
    })
}
wssrouter.get('/getChatHistory', async (ctx, next) => {
    let res = ctx.request.query;
    const {fid, tid, startTimestamp, endTimestamp} = res;
    // 初始化查询条件
    const query = {
        fid: {
            $in: [fid, tid]
        },
        tid: {
            $in: [fid, tid]
        }
    };

    // 根据传入的时间戳动态构建查询条件
    if (startTimestamp) {
        query.time = query.time || {};
        query.time.$gt = new Date(parseInt(startTimestamp));
    }
    if (endTimestamp) {
        query.time = query.time || {};
        query.time.$lt = new Date(parseInt(endTimestamp));
    }

    try {
        // 查询符合条件的十条数据
        const messages = await msg.find(query)
            .sort({time: -1}) // 按创建时间降序排序
            .limit(10); // 限制结果为十条

        response.success(ctx, {data: messages.sort((a, b) => a.time - b.time)});
    } catch (error) {
        response.error(ctx, {message: '查询聊天记录时出错', error: error.message});
    }
});
wssrouter.get('/userinfo', async (ctx, next) => {
    let res = ctx.request.query
    const {fid} = res
    let userinfo = await user.findOne({
        _id: fid
    })
    if (userinfo) {
        ctx.body = {
            code: 200,
            data: userinfo
        }
    } else {
        ctx.body = {
            code: 201,
            msg: "error"
        }
    }

})
wssrouter.post('/muserinfo', async (ctx, next) => {
    let res = ctx.request.body
    const {id, name} = res
    let userinfo = await user.findOneAndUpdate({
        _id: id
    }, {
        $set: {
            userName: name
        }
    }, {returnDocument: "after"})
    ctx.body = {
        code: 200,
        data: userinfo
    }
})
wssrouter.post('/modifyUserInfo', async (ctx, next) => {
    let res = ctx.request.body
    let ures = await user.findOne({
        _id: res.fdata._id
    })
    if (ures) {
        const messageToUpdate = ures.lastMsg.find(user =>
            user.fid == res.sdata.fid && user.tid == res.sdata.tid
        )
        messageToUpdate.unreadnum += 1
        let ffres = await ures.save()
        if (ffres) {
            let msglist = await user.find()

            ctx.body = {
                code: 200,
                data: msglist
            }
        }

    }


})
wssrouter.post('/readUnreadInfo', async (ctx, next) => {
    let res = ctx.request.body
    let ures = await user.findOne({
        _id: res.fdata._id
    })
    if (ures) {
        const messageToUpdate = ures.lastMsg.find(user =>
            user.fid == res.sdata.fid && user.tid == res.sdata.tid
        )
        messageToUpdate.unreadnum = 0
        let ffres = await ures.save()
        if (ffres) {
            let msglist = await user.find()
            ctx.body = {
                code: 200,
                data: msglist
            }
        }

    }


})
wssrouter.get('/sendEmail', async (ctx, next) => {
//待完善邮件发送

})
const sendEmail = async () => {
    return new Promise(async (resolve, reject) => {
        let toList = ['2954020052@qq.com', '3289391259@qq.com']
        for (const list of toList) {
            var mailOption = {
                from: '1078118049@qq.com', //发件人
                to: list, //收件人
                subject: `宏通聊天消息提醒请打开以下链接或者APP查看详情`, //标题
                html: `
 <div
style="
width: 100vw;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2),
0 6px 20px 0 rgba(0, 0, 0, 0.19);
"
>
<div
style="
background-color: #4caf50;
color: white;
 display: flex;align-items: center;justify-content: center;
font-size: 40px;
height: 200px;
"
>
<div>${`宏通聊天消息提醒请打开以下链接或者APP查看详情`}</div>

</div>

<div style="height: 100px;display: flex;justify-content: center; align-items: center;">
<p><a href='http://47.98.220.209:2333/chat'>宏通聊天</a></p>
</div>
</div>
 `
            }
            await transport.sendMail(mailOption, (err, res) => {
                if (err) {//执行错误
                    console.log(err)
                    reject(0)
                } else {
                    resolve(1)
                }
                transport.close(); // 如果没用，则关闭连接池
            })
        }
    })

}
module.exports = {
    WebSocketApi: (wss) => {
        // 当有客户端连接时
        wss.on('connection', async function connection(ws, req, next) {
            let vres = await verify(req, next)
            if (!vres) {
                console.log('Invalid token, terminating connection');
                ws.send(JSON.stringify({
                    type: 'connect',
                    data: {
                        code: 401,
                        message: 'Invalid token, terminating connection'
                    }
                }))
                ws.terminate(401, '非法'); // 断开连接
                return
            }

            ws.send(JSON.stringify({
                type: 'ping',
                data: 'ping'
            }))
            var timeout;
            var heartbeatInterval
            // 当收到消息时
            heartbeatInterval = setInterval(() => {
                if (!ws.isAlive) {
                    console.log('心跳异常，断开连接')
                    ws.terminate() // 终止连接
                    clearInterval(heartbeatInterval) // 清除定时器
                }
            }, HEARTBEAT_INTERVAL);
            ws.on('message', async function incoming(message) {
                let fobj = JSON.parse(message);
                let obj = fobj.data
                if (fobj.type === 'pong') {
                    ws.isAlive = true; //接收到pong响应，更新isAlive状态
                    timeout = setTimeout(() => {
                        ws.send(JSON.stringify({
                            type: 'ping',
                            data: 'ping'
                        }))
                        ws.isAlive = false;
                    }, CLIENT_TIMEOUT)
                }
                if (fobj.type === 'disconnect') {
                    console.log(obj)
                } else if (fobj.type === 'connect') {
                    //非消息 用户链接
                    if (!uws.map(e => e.uid).includes(obj.uid)) {
                        //如果没有此用户
                        ws.uid = obj.uid
                        uws.push(ws)
                        refreshOrCreateUserInfo(uws, obj.uid)
                        console.log('wss新增连接')
                    } else {
                        let index = uws.findIndex(e => e.uid === obj.uid)
                        ws.uid = obj.uid
                        uws[index] = ws
                        refreshOrCreateUserInfo(uws, obj.uid)
                        console.log('wss更新连接')
                    }
                } else if (fobj.type === 'message') {
                    if (obj.opType === 'msg') {
                        await msg.create(
                            obj
                        ).catch(err => {
                            response.error(ctx, {message: '发送失败'})
                        })
                        dealLastWord(obj.fid,
                            {
                                ...obj,
                                lastword: obj.content
                            }
                        ).then(res => {
                            dealLastWord(obj.tid,
                                {
                                    ...obj,
                                    lastword: obj.content
                                }
                            ).then(() => {
                                console.log('接受消息成功，文本')
                                refreshListInfo(uws)
                            }).then(async () => {
                                let msglist = await msg.find({
                                    fid: {
                                        $in: [obj.fid, obj.tid]
                                    },
                                    tid: {
                                        $in: [obj.fid, obj.tid]
                                    },
                                    time: {
                                        $lt: new Date(parseInt(Date.now()))
                                    }

                                }).sort({time: -1}).limit(10); // 限制结果为十条
                                uws.forEach((e, i) => {
                                    if (
                                        [obj.fid, obj.tid].includes(e.uid)
                                    ) {
                                        let obj = {
                                            type: 'message',
                                            data: msglist
                                        }
                                        e.send(JSON.stringify(obj))
                                    }
                                })
                            })
                        })
                    } else if (obj.opType === 'file') {
                        msg.create(
                            obj
                        )
                        dealLastWord(obj.fid,
                            {
                                ...obj,
                                lastword: obj.content
                            }
                        ).then(res => {
                            dealLastWord(obj.tid,
                                {
                                    ...obj,
                                    lastword: obj.content
                                }
                            ).then(() => {
                                refreshListInfo(uws)
                            }).then(async () => {
                                let msglist = await msg.find({
                                    fid: {
                                        $in: [obj.fid, obj.tid]
                                    },
                                    tid: {
                                        $in: [obj.fid, obj.tid]
                                    },
                                    time: {
                                        $lt: new Date(parseInt(Date.now()))
                                    }

                                }).sort({time: -1}).limit(10); // 限制结果为十条

                                uws.forEach((e, i) => {
                                    if (
                                        [obj.fid, obj.tid].includes(e.uid)
                                    ) {

                                        let obj = {
                                            type: 'message',
                                            data: msglist
                                        }
                                        e.send(JSON.stringify(obj))
                                    }
                                })
                            })
                        })
                    }
                }


            });

            // 当连接关闭时
            ws.on('close', function () {
                user.findOne({
                    _id: ws.uid
                }).then(res => {
                    if (res) {
                        user.findOneAndUpdate(
                            {
                                _id: res._id,
                            },
                            {$set: {isOnline: false, logoutTime: new Date().getTime()}},
                            {returnDocument: "after"}).then(async res => {
                            console.error(res._id, '客户端断开连接');
                            let list = await user.find()
                            uws.forEach((e, i) => {
                                let obj = {
                                    type: 'list',
                                    data: list
                                }
                                e.send(JSON.stringify(obj))
                                if (i === uws.length - 1) {
                                    console.error(`${ws.uid}群发断开连接信息`);
                                }
                            })
                        })
                    }
                })
                clearInterval(heartbeatInterval);
                clearTimeout(timeout); // 确保清除所有定时器
            });
        });
    },
    wssrouter: wssrouter
}

